using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;

namespace WPFTemplateLib.WpfConverters.Core
{
	/// <summary>
	/// Func 委托（带一个参数和一个返回值）值转换器类型。（可在 VM 中声明一个此类型的值转换器以供前台绑定）<para/>
	/// 来自：https://blog.coldwind.top/posts/valueconverter-tips-and-tricks/
	/// </summary>
	/// <example>
	/// <![CDATA[
	/// 声明：
	/// public static FuncValueConverter<string, int> StringToIntConverter { get; } = new(s => int.Parse(s));
	/// 绑定：
	/// Converter={x:Static local:MainViewModel.StringToIntConverter}
	/// ]]>
	/// </example>
	public sealed class FuncValueConverter<TIn, TOut> : IValueConverter
	{
		private readonly Func<TIn, TOut> _convert;

		public FuncValueConverter(Func<TIn, TOut> convert)
		{
			_convert = convert;
		}

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(value is not TIn t)
			{
				if(value is null)
				{
					return default(TOut);
				}

				//能被内置类型转换器装换;
				if(TypeDescriptor.GetConverter(typeof(TIn)).CanConvertFrom(value.GetType()))
				{
					t = (TIn)TypeDescriptor.GetConverter(typeof(TIn)).ConvertFrom(value);
				}
				else
				{
					return Binding.DoNothing;
				}
			}

			return _convert(t);
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return Binding.DoNothing;
		}
	}
}
